package com.square.service.gateway.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.square.service.gateway.filter.LoginAuthCheckGateWayFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 路由配置
 *
 * @author : 王苏
 * @since : 2021/4/23 18:57
 */
@Configuration
public class RoutesConfig {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        //登录认证局部过滤器
        LoginAuthCheckGateWayFilter loginAuthCheck = new LoginAuthCheckGateWayFilter();
        return builder.routes()
                .route("auth", r -> r.path("/auth/**").filters(f -> f.stripPrefix(1)).uri("lb://auth"))
                .route("forum", r -> r.path("/forum/**").filters(f -> f.stripPrefix(1).filter(loginAuthCheck)).uri("lb://forum"))
                .route("member", r -> r.path("/member/**").filters(f -> f.stripPrefix(1).filter(loginAuthCheck)).uri("lb://member"))
                .build();
    }


    /**
     * 自定义错误信息
     *
     * @param exchange
     * @param r
     * @return
     */
    public static Mono<Void> errorInfo(ServerWebExchange exchange, R<?> r) {
        return Mono.defer(() -> {
            byte[] bytes = JSON.toJSONBytes(r);
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Flux.just(buffer));
        });
    }
}
